package com.example.javabasic.thread.classone.demo4;

/**
 * 测试 synchronized  关键字
 * 视频地址: https://www.bilibili.com/video/BV1L4411i7eW?p=23
 */
public class SyncTest {
    private static volatile int n = 1;
    private static final int MAX = 100;
    private static final Object object = new Object();

    public static void main(String[] args) {
        Runnable runnable = () -> {
            while (true) {
                Boolean aBoolean = test2();
                if(aBoolean){
                    break;
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread t1 = new Thread(runnable, "t1");
        Thread t2 = new Thread(runnable, "t2");
        Thread t3 = new Thread(runnable, "t3");
        Thread t4 = new Thread(runnable, "t4");
        //设置t1的优先级
        t1.start();
        t2.start();
        t3.start();
        t4.start();

    }


    /**
     * 测试同步代码块
     */
    public static void test1() {
        Runnable runnable = () -> {
            while (true) {
                //同步代码块, 需要有一个对象作为锁对象
                //同步代码块 支持任意对象作为对象监视器 来实现同步功能,  synchronized() 的 括号中  可以是任意一个实例对象
                synchronized (object) {
                    if (n > MAX) {
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + n++);
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread t1 = new Thread(runnable, "t1");
        Thread t2 = new Thread(runnable, "t2");
        Thread t3 = new Thread(runnable, "t3");
        Thread t4 = new Thread(runnable, "t4");
        //设置t1的优先级
        t1.setPriority(2);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

    /**
     * 测试同步方法
     */
    //  方法锁是 this 锁  也就是对象锁,  静态方法是类锁
    // 锁的字节码为  monitor
    public synchronized static Boolean test2() {
        if(n<MAX){
            System.out.println(Thread.currentThread().getName() + ":" + n++);
            return false;
        }
        return true;
    }

    /**
     * 同步代码块2
     * @return
     */
    public Boolean test3(){
        synchronized (this){
            if(n<MAX){
                System.out.println(Thread.currentThread().getName() + ":" + n++);
                return false;
            }
        }
        return true;
    }




}
